# 用户登录、鉴权、退出相关方法
import json
from django.http import JsonResponse
from .models import UserModel
from djangomodel.err import MethodNotAllowedErr
from django.core.cache import cache
from djangomodel.tools import make_token
from djangomodel.settings import TOKENTIMEOUT

# 用户登录方法
def login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username').strip()
        passwd = data.get('passwd').strip()
        user = UserModel.objects.filter(username=username,passwd=passwd)
        if user.exists():
            # 登录成功
            user = user[0]
            userid = user.uuid.__str__()
            token = make_token(userid)
            cache.set(token,userid,timeout=TOKENTIMEOUT)
            return JsonResponse({"status": 200,"msg":"登录成功！","token":token})
        else:
            return JsonResponse({"status": 400, "msg": "用户名或密码错误！"})
    else:
        raise MethodNotAllowedErr()

# 用户登出
def logout(request):
    if request.method == 'GET':
        token = request.META.get("HTTP_AUTHORIZATION")
        cache.delete(token)
        return JsonResponse({"status": 200,"msg":"用户已退出!"})
    else:
        raise MethodNotAllowedErr()